<?php

namespace Ignus\View;

use Ignus\View\Error\Syntax;

class TokenStream
{
    /**
     * @var \Ignus\View\Token[]
     */
    protected $tokens;

    /**
     * @var integer
     */
    protected $current;

    /**
     * @var string
     */
    protected $filename;

    public function __construct(array $tokens, $filename = null)
    {
        $this->tokens     = $tokens;
        $this->current    = 0;
        $this->filename   = $filename;
    }

    /**
     * @return string
     */
    public function __toString()
    {
        return implode("\n", $this->tokens);
    }

    /**
     * @return \Ignus\View\Token
     */
    public function next()
    {
        if (!isset($this->tokens[++$this->current])) {
            throw new Syntax('Unexpected end of template', -1, $this->filename);
        }

        return $this->tokens[$this->current - 1];
    }

    /**
     * @return \Ignus\View\Token
     */
    public function expect($type, $value = null, $message = null)
    {
        $token = $this->tokens[$this->current];
        if (!$token->test($type, $value)) {
            $line = $token->getLine();
            throw new Syntax(sprintf('%sUnexpected token "%s" of value "%s" ("%s" expected%s)',
                $message ? $message.'. ' : '',
                Token::typeToEnglish($token->getType(), $line), $token->getValue(),
                Token::typeToEnglish($type, $line), $value ? sprintf(' with value "%s"', $value) : ''),
                $line,
                $this->filename
            );
        }
        $this->next();

        return $token;
    }

    /**
     * @return \Ignus\View\Token
     */
    public function look($number = 1)
    {
        if (!isset($this->tokens[$this->current + $number])) {
            throw new Syntax('Unexpected end of template', -1, $this->filename);
        }

        return $this->tokens[$this->current + $number];
    }

    /**
     * @return boolean
     */
    public function test($primary, $secondary = null)
    {
        return $this->tokens[$this->current]->test($primary, $secondary);
    }

    /**
     * @return boolean
     */
    public function isEOF()
    {
        return $this->tokens[$this->current]->getType() === Token::EOF_TYPE;
    }

    /**
     * @return \Ignus\View\Token
     */
    public function getCurrent()
    {
        return $this->tokens[$this->current];
    }

    /**
     * @return string
     */
    public function getFilename()
    {
        return $this->filename;
    }
}
